package org.example.netty.zdyxieyi;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ClientDemo {
    public static void main(String[] args) {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 14, 4, 0, 0));
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new MessageCodec());
                        pipeline.addLast(new MessageSimpleChannelInboundHandler());
                    }
                })
                .connect("localhost", 8080);

        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                log.info("连接成功");
            } else {
                log.info("连接失败");
            }
        });
    }

}
